import React, { PureComponent, Component } from 'react'
import {
  BackHandler,
  Text,
  Animated,
  Easing,
  View,
  StatusBar,
  Modal,
  ActivityIndicator,
} from 'react-native'
import {
  StackNavigator,
  TabNavigator,
  TabBarBottom,
  addNavigationHelpers,
  NavigationActions,
} from 'react-navigation'
import { connect } from 'react-redux'
import Icon from 'react-native-vector-icons/Ionicons'
import SplashScreen from 'react-native-splash-screen'
import { createAction, getAsyncStorage, removeAsyncStorage } from './utils'
import { toast } from './utils/toast'

import FixHeader from './component/FixHeader'

import Signin from './containers/Signin'
import Signup from './containers/Signup'
import Password from './containers/Password'
import Home from './containers/Home'
import Search from './containers/Search'
import Category from './containers/Category'
import Cart from './containers/Cart'
import CartSingle from './containers/CartSingle'
import Account from './containers/Account'
import Address from './containers/Address'
import EditAddress from './containers/EditAddress'
import GoodsList from './containers/GoodsList'
import Goods from './containers/Goods'
import OrderConfirm from './containers/OrderConfirm'
import Payment from './containers/Payment'
import OrderList from './containers/OrderList'
import OrderDetail from './containers/OrderDetail'
import Setting from './containers/Setting'
import Suggestion from './containers/Suggestion'
import Comment from './containers/Comment'
import About from './containers/About'
import Browser from './containers/Browser'
import Village from './containers/Village'
import PaySuccess from './containers/PaySuccess'
import VillageChoose from './containers/VillageChoose'
import Avatar from './containers/Avatar'
import Coupon from './containers/Coupon'

const HomeNavigator = TabNavigator(
  {
    Home: { screen: Home },
    Category: {
      screen: Category,

      navigationOptions: props => {
        const { navigation } = props
        return {
          title: null,
          header: <FixHeader navigation={navigation} />,
          tabBarLabel: '分类',
          tabBarIcon: ({ focused, tintColor }) => (
            <Icon
              name="ios-list"
              style={{ color: focused ? tintColor : 'gray' }}
              size={30}
            />
          ),
        }
      },
    },
    Cart: { screen: Cart },
    Account: { screen: Account },
  },
  {
    tabBarComponent: TabBarBottom,
    tabBarPosition: 'bottom',
    swipeEnabled: false,
    animationEnabled: false,
    lazyLoad: true,
    tabBarOptions: {
      activeTintColor: '#0398ff',
      style: {
        backgroundColor: 'white',
        elevation: 5, // for android
        shadowOffset: { width: 0, height: 0 },
        shadowColor: '#e5e5e5',
        shadowOpacity: 0.85,
        shadowRadius: 5,
      },
    },
  }
)
const Login = StackNavigator(
  {
    Signin: { screen: Signin },
    Signup: { screen: Signup },
    Password: { screen: Password },
  },
  {
    headerMode: 'float',
    navigationOptions: {
      headerBackTitleStyle: { color: '#333' },
      headerTintColor: '#333',
      headerTitleStyle: {
        alignSelf: 'center',
      },
    },
  }
)

const defaultGetStateForAction = Login.router.getStateForAction

Login.router.getStateForAction = (action, state) => {
  console.log(action)
  if (state && action.actionKey && action.actionKey === 'GoToRoute') {
    const index = state.routes.findIndex(
      item => item.routeName === action.routeName
    )
    const routes = state.routes.slice(0, index + 1)

    return {
      ...state,
      routes,
      index,
    }
  }
  return defaultGetStateForAction(action, state)
}
const MainNavigator = StackNavigator(
  {
    HomeNavigator: { screen: HomeNavigator },
    CartSingle: { screen: CartSingle },
    Address: { screen: Address },
    EditAddress: { screen: EditAddress },
    GoodsList: {
      screen: GoodsList,
      navigationOptions: props => {
        const { navigation } = props
        return {
          title: null,
          header: (
            <FixHeader
              navigation={navigation}
              backgroundColor="white"
              backButton
            />
          ),
        }
      },
    },
    Goods: { screen: Goods },
    OrderConfirm: { screen: OrderConfirm },
    Payment: { screen: Payment },
    OrderList: { screen: OrderList },
    OrderDetail: { screen: OrderDetail },
    Setting: { screen: Setting },
    Suggestion: { screen: Suggestion },
    Comment: { screen: Comment },
    Browser: { screen: Browser },
    About: { screen: About },
    PaySuccess: { screen: PaySuccess },
    Coupon:{screen:Coupon},
  },
  {
    headerMode: 'float',
    navigationOptions: {
      headerBackTitleStyle: { color: '#333' },
      headerTintColor: '#333',
    },
  }
)

const AppNavigator = StackNavigator(
  {
    Main: { screen: MainNavigator },
    Login: { screen: Login },
    Village: { screen: Village },
    Avatar:{screen:Avatar},
    
  },
  {
    headerMode: 'none',
    mode: 'modal',
    navigationOptions: {
      gesturesEnabled: false,
    },

    transitionConfig: () => ({
      transitionSpec: {
        duration: 300,
        easing: Easing.out(Easing.poly(4)),
        timing: Animated.timing,
      },
    }),
  }
)

const InitNavigator = StackNavigator({
  Village: { screen: Village },
})
function getCurrentScreen(navigationState) {
  if (!navigationState) {
    return null
  }
  const route = navigationState.routes[navigationState.index]
  if (route.routes) {
    return getCurrentScreen(route)
  }
  return route.routeName
}

class Router extends Component {
  constructor(props) {
    super(props)
    this.state = {
      location: false,
      requestTimes: 0,
    }
  }
  componentWillMount() {
    BackHandler.addEventListener('hardwareBackPress', () => this.backHandle())
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', () =>
      this.backHandle()
    )
  }
  componentDidMount() {
    // removeAsyncStorage('LOCATION')
    getAsyncStorage('LOCATION')
      .then(data => {
        this.setState({ location: !!data, requestTimes: 1 })
        SplashScreen.hide()
      })
      .catch(e => {
        this.setState({ location: false, requestTimes: 1 })
        SplashScreen.hide()
      })
  }

  backHandle = () => {
    if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
      // 最近2秒内按过back键，可以退出应用。
      return false
    }

    this.lastBackPressed = Date.now()
    toast('再按一次退出应用')
    return true
    /**
    const currentScreen = getCurrentScreen(this.props.router)
    if (currentScreen === 'Login') {
      return true
    }
    if (currentScreen !== 'Home') {
      // this.props.navigation.dispatch(NavigationActions.back())
      return true
    }
    return false
    * */
  }
  replacePage = () => {
    this.setState({ location: true })
  }
  render() {
    const { location, requestTimes } = this.state

    if (requestTimes == 0) {
      return <View />
    }
    // 是否有历史地位信息
    if (!location) {
      return <VillageChoose replacePage={this.replacePage} />
    }
    return <AppNavigator />
  }
}

export default Router
